﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Model01.Objects;

namespace Model01.Logic
{
    /// <summary>
    /// Represents the two-dimensional map.
    /// </summary>
    [Serializable]
    public class Map
    {
        #region Fields

        private byte[,] passability;
        private readonly Size size;

        #endregion

        /// <summary>
        /// Creates new map.
        /// </summary>
        /// <param name="size">Size of a map.</param>
        public Map(Size size)
        {
            passability = new byte[size.Width, size.Height];
            this.size = size;
        }

        /// <summary>
        /// Creates new map.
        /// </summary>
        /// <param name="passability">Passability matrix of a map.</param>
        public Map(byte[,] passability)
        {
            this.passability = passability;
            this.size = new Size(passability.GetLength(1), passability.GetLength(0));
        }

        #region Methods

        /// <summary>
        /// Load map from file fileName.
        /// </summary>
        /// <param name="fileName">Name of file from which map will be loaded.</param>
        /// <returns></returns>
        /// <exception cref="System.Runtime.Serialization.SerializationException"/>
        public static Map FromFile(string fileName)
        {
            Map map = null;
            FileStream fs = new FileStream(fileName, FileMode.Open);
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                map = (Map)formatter.Deserialize(fs);
                return map;
            }
            catch (SerializationException e)
            {
                throw e;
            }
            finally
            {
                fs.Close();
            }
        }

        #endregion

        #region Properties

        public byte this[int x, int y]
        {
            get { return passability[y, x]; }
        }

        public Size Size
        {
            get { return size; }
        }

        #endregion
    }
}
